package mo.offer_special;

import java.util.ArrayList;
import java.util.List;

public class L087 {

    private List<String> ans = new ArrayList<>();

    public List<String> restoreIpAddresses(String s) {
        if (s.length() < 4 || s.length() > 12) {
            return ans;
        }
        List<String> combination = new ArrayList<>();
        generate(combination, s, 0, 0);
        return ans;
    }

    private void generate(List<String> combination, String s, int splitTimes, int index) {
        if (splitTimes == 4 && index == s.length()) {
            ans.add(String.join(".", combination));
        }
        for (int i = 1; i <= 3; i++) {
            if (index + i <= s.length()) {
                String ip = s.substring(index, index + i);
                if (isValid(ip)) {
                    combination.add(ip);
                    generate(combination, s, splitTimes+1, index+i);
                    combination.remove(combination.size()-1);
                }
            }
        }
    }

    private boolean isValid(String ip) {
        if (ip.length() == 1) {
            return true;
        } else {
            if (ip.charAt(0) == '0') {
                return false;
            }
            if (Integer.parseInt(ip) > 255) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        L087 test = new L087();
        System.out.println(test.restoreIpAddresses("10203040"));
    }

}
